package fr.web325.dao;

import fr.web325.utils.QueryRunnerUtils;
import fr.web325.bean.Order;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class OrderDao {
    public Class<Order> orderClass = Order.class;

    // 查询所有订单列表
    public List<Order> getOrderList() throws SQLException {
        // 获取数据库连接池对象
        QueryRunner qr = new QueryRunner(QueryRunnerUtils.getDateSource());
        // 查询并返回user对象
        return qr.query("select * from orders left join user u on u.id = orders.user_id", new BeanListHandler<>(orderClass));
    }


    // 根据ID查询订单
    public Order getOrderById(String id) throws SQLException {
        // 获取数据库连接池对象
        QueryRunner qr = new QueryRunner(QueryRunnerUtils.getDateSource());
        // 查询并返回user对象
        return qr.query("select * from orders where id=?", new BeanHandler<>(orderClass), id);
    }

    // 根据ID修改订单
    public Boolean editOrder(Order order) throws SQLException {
        // 获取数据库连接池对象
        QueryRunner qr = new QueryRunner(QueryRunnerUtils.getDateSource());
        return qr.update("update orders set receiverName=?,receiverAddress=?,receiverPhone=? where id=?", order.getReceiverName(), order.getReceiverAddress(), order.getReceiverPhone(), order.getId()) > 0;
    }


    // 根据id删除order
    public Boolean removeOrderById(String id) throws SQLException {
        // 获取数据库连接池对象
        QueryRunner qr = new QueryRunner(QueryRunnerUtils.getDateSource());
        return qr.update("delete from orders where id=?", id) > 0;
    }
}
